<?php
namespace Admin\Model;
use Think\Model;

class OrderModel extends Model{
    protected $connection = 'DB_CONFIG2';
//     protected $tablePrefix = 'shop_';

	/**
	 * 根据条件，返回订单总数
	 * @param string $where
	 * @return number|NULL
	 */
	public function getOrdersCount($where=null){
		$orderNum = $this->alias('o')->where($where)->select();
		if ($orderNum) {
			$orderNum = count($orderNum);
			return $orderNum;
		}else{
			return null;
		}
	}

	/**
	 * 获取订单列表，并分页，返回订单列表
	 * @param unknown $page
	 * @param string $where
	 * @return unknown|NULL
	 */
	public function getOrderList($page,$where=null,$p=null,$type="select"){
	    if($type=="select"){
	        $orderList = $this->field('o.id as order_id,o.create_time as o_create_time,o.*,oi.*,uc.*,u.*')->
	        alias('as o')->
	        join(C('DB_PREFIX').'order_info as oi ON o.ordersn = oi.ordersn')->
	        join(C('DB_PREFIX').'user_car as uc ON oi.user_car_id = uc.id')->
	        join(C('DB_PREFIX').'user as u ON oi.openid = u.openid')->
	        where($where)->order('o.id desc,o.wash_status asc')->page($p)->select();
	    }
	    else if($type=="find"){
	        $orderList = $this->field('o.id as order_id,o.create_time as o_create_time,o.*,oi.*,uc.*,u.*')->alias('as o')->
	        join(C('DB_PREFIX').'order_info as oi ON o.ordersn = oi.ordersn')->
	        join(C('DB_PREFIX').'user_car as uc ON oi.user_car_id = uc.id')->
	        join(C('DB_PREFIX').'user as u ON oi.openid = u.openid')->
	        where($where)->order('o.wash_status asc')->find();
	    }

		if ($orderList) {
			return $orderList;
		}else{
			return null;
		}
	}

	public function save_delivery_info($orderId,$ordersDelivery){
		startTrans($this);
		$this->deliveryModel = M('Delivery');
		$ordersDelivery['send_time'] = strtotime($ordersDelivery['send_time']);
 		$DeliveryPrice = $this->deliveryModel->field('delivery_price')->where('id='.$ordersDelivery['delivery_id'])->find();
 		$ordersDelivery['delivery_price'] = $DeliveryPrice['delivery_price'];
		$update = $this->where(array('id'=>$orderId))->save($ordersDelivery);
		if($update){
			return true;
		}else{
			rollBack();
			return false;
		}
	}

}

?>
